using CCWin;
using ERP_SaaS_WinForm.生产工单_报工_工序;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.物料管理
{
    public partial class SelectProductionOrderForm : CCSkinMain
    {
        private string urls;
        // 存储选中的工单
        public ProductionOrders SelectedProductionOrder { get; private set; }
        
        // 是否允许多选
        public bool AllowMultipleSelection { get; set; } = false;

        public SelectProductionOrderForm()
        {
            InitializeComponent();
            InitializeForm();
            this.Load += SelectProductionOrderForm_Load;
            urls = Apllo.ApiBaseUrl;
        }

        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitializeForm()
        {
            // 设置窗体属性
            this.Text = "选择工单";
            this.Size = new Size(1000, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
        }

        /// <summary>
        /// 初始化数据网格
        /// </summary>
        private void InitializeDataGridView()
        {
            if (dgvProductionOrders != null)
            {
                dgvProductionOrders.AutoGenerateColumns = false;
                dgvProductionOrders.AllowUserToAddRows = false;
                dgvProductionOrders.AllowUserToDeleteRows = false;
                dgvProductionOrders.ReadOnly = true;
                dgvProductionOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvProductionOrders.MultiSelect = false;
                dgvProductionOrders.RowHeadersVisible = false;
                dgvProductionOrders.BackgroundColor = Color.White;
                dgvProductionOrders.ScrollBars = ScrollBars.Both;

                SetupColumns();
            }
        }

        /// <summary>
        /// 设置列
        /// </summary>
        private void SetupColumns()
        {
            if (dgvProductionOrders != null)
            {
                dgvProductionOrders.Columns.Clear();

                // 工单编号列
                DataGridViewTextBoxColumn codeColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "工单编号",
                    DataPropertyName = "ProductionOrdersCode",
                    Width = 120
                };
                dgvProductionOrders.Columns.Add(codeColumn);

                // 工单名称列
                DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "工单名称",
                    DataPropertyName = "ProductionOrdersName",
                    Width = 150
                };
                dgvProductionOrders.Columns.Add(nameColumn);

                // 产品名称列
                DataGridViewTextBoxColumn productNameColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "产品名称",
                    DataPropertyName = "ProductName",
                    Width = 120
                };
                dgvProductionOrders.Columns.Add(productNameColumn);

                // 产品编号列
                DataGridViewTextBoxColumn productCodeColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "产品编号",
                    DataPropertyName = "ProductCode",
                    Width = 120
                };
                dgvProductionOrders.Columns.Add(productCodeColumn);

                // 规格型号列
                DataGridViewTextBoxColumn specColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "规格型号",
                    DataPropertyName = "SpecificationModel",
                    Width = 120
                };
                dgvProductionOrders.Columns.Add(specColumn);

                // 单位列
                DataGridViewTextBoxColumn unitColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "单位",
                    DataPropertyName = "Unit",
                    Width = 80
                };
                dgvProductionOrders.Columns.Add(unitColumn);

                // 状态列
                DataGridViewTextBoxColumn stateColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "状态",
                    DataPropertyName = "State",
                    Width = 100
                };
                dgvProductionOrders.Columns.Add(stateColumn);
            }
        }

        /// <summary>
        /// 查询并绑定工单数据
        /// </summary>
        private async Task QueryAndBindAsync()
        {
            string baseUrl = urls+"/api/ProductionOrders/ProductionOrdersCommand";
            string productionOrdersCode = string.Empty;
            string productionOrdersName = string.Empty;
            
            // 安全获取文本框内容
            if (txtProductionOrdersCode != null && !string.IsNullOrWhiteSpace(txtProductionOrdersCode.Text))
            {
                productionOrdersCode = txtProductionOrdersCode.Text.Trim();
            }
            if (txtProductionOrdersName != null && !string.IsNullOrWhiteSpace(txtProductionOrdersName.Text))
            {
                productionOrdersName = txtProductionOrdersName.Text.Trim();
            }
            
            // 构建查询参数
            var queryParams = new List<string>();
            if (!string.IsNullOrEmpty(productionOrdersCode))
            {
                queryParams.Add($"ProductionOrdersCode={Uri.EscapeDataString(productionOrdersCode)}");
            }
            if (!string.IsNullOrEmpty(productionOrdersName))
            {
                queryParams.Add($"ProductionOrdersName={Uri.EscapeDataString(productionOrdersName)}");
            }
            
            if (queryParams.Count > 0)
            {
                baseUrl += "?" + string.Join("&", queryParams);
            }

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(baseUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    // 解析API响应
                    dynamic apiResponse = JsonConvert.DeserializeObject(jsonResponse);
                    
                    if (apiResponse != null && apiResponse.code == 200)
                    {
                        var data = apiResponse.data;
                        var pageDatas = data?.pageDatas ?? data?.data;
                        
                        if (pageDatas != null)
                        {
                            var productionOrdersList = JsonConvert.DeserializeObject<List<ProductionOrders>>(pageDatas.ToString());
                            
                            if (productionOrdersList != null && productionOrdersList.Count > 0)
                            {
                                // 绑定数据到DataGridView
                                if (dgvProductionOrders != null)
                                {
                                    dgvProductionOrders.DataSource = productionOrdersList;
                                    
                                    // 默认选中第一行
                                    if (dgvProductionOrders.Rows.Count > 0 && dgvProductionOrders.Columns.Count > 0)
                                    {
                                        dgvProductionOrders.Rows[0].Selected = true;
                                        dgvProductionOrders.CurrentCell = dgvProductionOrders.Rows[0].Cells[0];
                                    }
                                }
                            }
                            else
                            {
                                if (dgvProductionOrders != null)
                                {
                                    dgvProductionOrders.DataSource = null;
                                }
                                MessageBox.Show("未找到相关工单数据");
                            }
                        }
                        else
                        {
                            if (dgvProductionOrders != null)
                            {
                                dgvProductionOrders.DataSource = null;
                            }
                            MessageBox.Show("未找到相关工单数据");
                        }
                    }
                    else
                    {
                        MessageBox.Show($"查询失败: {apiResponse?.message ?? "未知错误"}");
                        if (dgvProductionOrders != null)
                        {
                            dgvProductionOrders.DataSource = null;
                        }
                    }
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"网络请求失败: {ex.Message}");
                    if (dgvProductionOrders != null)
                    {
                        dgvProductionOrders.DataSource = null;
                    }
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"数据解析失败: {ex.Message}");
                    if (dgvProductionOrders != null)
                    {
                        dgvProductionOrders.DataSource = null;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}");
                    if (dgvProductionOrders != null)
                    {
                        dgvProductionOrders.DataSource = null;
                    }
                }
            }
        }

        /// <summary>
        /// 搜索按钮点击事件
        /// </summary>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private async void SelectProductionOrderForm_Load(object sender, EventArgs e)
        {
            InitializeDataGridView();
            await QueryAndBindAsync();
        }

        /// <summary>
        /// 确认选择按钮点击事件
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvProductionOrders != null && dgvProductionOrders.CurrentRow != null)
                {
                    var productionOrder = dgvProductionOrders.CurrentRow.DataBoundItem as ProductionOrders;
                    if (productionOrder != null)
                    {
                        SelectedProductionOrder = productionOrder;
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("请选择有效的工单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择一个工单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"选择工单失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 取消按钮点击事件
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        /// <summary>
        /// 双击行选择
        /// </summary>
        private void dgvProductionOrders_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                btnConfirm_Click(sender, e);
            }
        }

        /// <summary>
        /// 处理单元格格式化
        /// </summary>
        private void dgvProductionOrders_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 6 && e.Value != null) // 状态列
            {
                if (int.TryParse(e.Value.ToString(), out int state))
                {
                    string stateText = GetStateText(state);
                    e.Value = stateText;
                    e.FormattingApplied = true;
                }
            }
        }

        /// <summary>
        /// 获取状态文本
        /// </summary>
        private string GetStateText(int state)
        {
            switch (state)
            {
                case 0: return "待排产";
                case 1: return "未开始";
                case 2: return "进行中";
                case 3: return "已完成";
                case 4: return "已暂停";
                case 5: return "已关闭";
                default: return "未知";
            }
        }
    }
} 